package com.bootdo.cms.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.bootdo.cms.domain.CmsFileDO;
import com.bootdo.cms.domain.VideoDO;
import com.bootdo.cms.service.CmsFileService;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.domain.FileForm;
import com.bootdo.common.utils.*;
import com.bootdo.system.domain.UserDO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.validation.Valid;
import java.io.*;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author SiMan
 * @date 2019/12/18 10:20
 */
@Controller
@RequestMapping("/front/submit")
public class SubmitController {
	String prefix = "/front";

	@Autowired
	BootdoConfig bootdoConfig;
	@Autowired
	CmsFileService cmsFileService;

	@GetMapping("/upload")
	public String upload(Map<String, Object> model) {
		return "upload";
	}

	@RequestMapping("/saveUpload")
	@ResponseBody
	public void upload(MultipartHttpServletRequest request) {
		String fileName = request.getParameter("name");
		String parentFile = null;
		String[] split = StrUtil.splitToArray(fileName,'.');
		String suffix = split[split.length - 1];
		switch (suffix) {
			case "mp4":
				parentFile = "video";
				break;
			case "mp3":
				parentFile = "music";
				break;
			case "jpg":
				parentFile = "image";
				break;
			case "docx":
				parentFile = "Office";
				break;
			case "pptx":
				parentFile = "Office";
				break;
			case "xlsx":
				parentFile = "Office";
				break;
			default:
				parentFile = "Else";
				break;
		}

		String guid = request.getParameter("guid");
		MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();

		MultipartFile multipartFile = multiFileMap.getFirst("file");
		try {
			InputStream in = multipartFile.getInputStream();

			String chunk = request.getParameter("chunk")==null?"0":request.getParameter("chunk");
			String path = bootdoConfig.getUploadPath() + File.separator +
					parentFile + File.separator +
					request.getParameter("id") + File.separator + guid;
			File exist = new File(path);
			if (!exist.exists()) {
				exist.mkdirs();
			}
			OutputStream out = new FileOutputStream(path + File.separator + chunk + "_" + request.getParameter("name"));
			byte[] bytes = new byte[1024];
			int len = -1;

			while ((len = in.read(bytes)) != -1) {
				out.write(bytes, 0, len);
			}
			out.close();
			in.close();


		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 文件合并
	 * @param guid
	 * @param realFileName
	 * @param chunks
	 * @param folder
	 */
	@PostMapping("/merge")
	@ResponseBody
	public R merge(String guid, String realFileName, int chunks, String folder ) {
		System.out.println("HE BIN HE BIN HE BIN HE BIN");

		CmsFileDO cmsFileDO = new CmsFileDO();
		String uuid = IdUtil.simpleUUID();
		String fileType = null;
		String parentFile = null;
		Long channelId = null;
		String suffix = realFileName.substring(realFileName.lastIndexOf(".") + 1);
		switch (suffix) {
			case "mp4":
				parentFile = "video";
				channelId = new Long(125);
				fileType = "video";
				break;
			case "rmvb":
				parentFile = "video";
				channelId = new Long(125);
				fileType = "video";
				break;
			case "mp3":
				parentFile = "music";
				channelId = new Long(126);
				fileType = "music";
				break;
			case "jpg":
				parentFile = "image";
				channelId = new Long(127);
				fileType = "image";
				break;
			case "png":
				parentFile = "image";
				channelId = new Long(127);
				fileType = "image";
				break;
			case "docx":
				parentFile = "Office";
				channelId = new Long(128);
				fileType = "Office";
				break;
			case "pptx":
				parentFile = "Office";
				channelId = new Long(128);
				fileType = "Office";
				break;
			case "xlsx":
				parentFile = "Office";
				channelId = new Long(128);
				fileType = "Office";
				break;
			default:
				parentFile = "Else";
				channelId = new Long(129);
				fileType = "Else";
				break;
		}
		String path = bootdoConfig.getUploadPath()+File.separator + File.separator +
				parentFile ;
		String path2 = bootdoConfig.getUploadPath()+File.separator+
				parentFile  + File.separator +
				folder + File.separator +
				guid;
		try {
			FileOutputStream  fileOutputStream = new FileOutputStream(path+File.separator+realFileName);
			byte[] buf = new byte[1024];
			for(int i=0;i<chunks;i++){
				File tempFile = new File(path2+File.separator+i+"_"+realFileName);
				InputStream inputStream = new FileInputStream(tempFile);
				int len = 0;
				while((len=inputStream.read(buf))!=-1){
					fileOutputStream.write(buf,0,len);
				}
				inputStream.close();
				//删除临时文件
				tempFile.delete();
			}
			fileOutputStream.close();
			FileUtil.deleteFile(new File(bootdoConfig.getUploadPath()+File.separator+
					parentFile  + File.separator +
					folder));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		cmsFileDO.setId(IdUtil.randomUUID());
		cmsFileDO.setFileName(realFileName);
		File file = new File(path+File.separator+realFileName);
		cmsFileDO.setFileSize(file.length());
		cmsFileDO.setUploadTime(LocalDateTime.now());
		cmsFileDO.setFileType(fileType);
		cmsFileDO.setUploadBy(ShiroUtils.getMember().getUsername());
		cmsFileDO.setChannelId(channelId);
		cmsFileDO.setFileUrl(path+File.separator+realFileName);
		cmsFileService.insert(cmsFileDO);

		return R.ok();
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("cms:video:list")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<CmsFileDO> fileList = cmsFileService.list(query);
		int total = cmsFileService.count(query);
		PageUtils pageUtils = new PageUtils(fileList, total);
		return pageUtils;
	}

	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("cms:video:remove")
	public R remove(String id){
		CmsFileDO cmsFileDO = cmsFileService.selectById(id);
		String path = bootdoConfig.getUploadPath() +
				cmsFileDO.getFileType()  + File.separator +
				cmsFileDO.getFileName();
		File file = new File(path);
		file.delete();
		if(cmsFileService.remove(id)>0){
			return R.ok();
		}
		return R.error();
	}


}
